<?php
namespace control;
/*
*档案保管类
*/


class cabinetClass extends adIndexClass
{
    private const page = 'cabinet'; # 权限
    private const table = 'archive_file'; # 数据表
    private const table_cabinet = 'archive_cabinet'; # 数据表
    private const title = '档案保管';

    public static function getDepartmentAll($data = []): string
    {
        // 条件
        $data['where'] = $data['where'] ?? "pid='0'";
        // 点击事件
        $data['click'] = $data['click'] ?? "replaceDetail(this,'" . self::page . "')";
        // 结果
        $result = find(['table' => self::table_cabinet, 'where' => $data['where'] . " order by list asc"]);
        $style = ($data['where'] == "pid='0'") ? '' : ' class="child-node"';
        $temp = "<ul {$style} {$data['where']}>";
        $textcontent_ico = "<span class='textcontent_ico'></span>";
        if ($result['array']) {
            foreach ($result['array'] as $value) {
                // 角标
                $arrow = "<span class='arrow'  onclick=\"liZoom($(this).parent())\"></span>";
                // 判断下级是否存在
                $data['where'] = " pid='{$value['id']}' ";
                $has = query(self::table_cabinet, $data['where']);
                $dots = "<div class='actionBlock none'>
                            <img data-pid='{$value['pid']}' title='添加同级' onclick=\"layer('" . self::page . "','catalog',{id:'" . suiji() . "',pid:'{$value['pid']}',type:'brother'})\" src='".root."img/control/list_copy.svg'>
                            <img data-pid='{$value['id']}' title='添加下级' onclick=\"layer('" . self::page . "','catalog',{id:'" . suiji() . "',pid:'{$value['id']}',type:'children'})\" src='".root."img/control/list_add.svg'>
                            <img data-id='{$value['id']}' title='编辑' onclick=\"layer('" . self::page . "','catalog',{id:'" . $value['id'] . "'})\" src='".root."img/control/edit.svg'>
                            <img data-id='{$value['id']}' title='删除' onclick=\"layer('" . self::page . "','operate',{'act': 'delType',id:'" . $value['id'] . "'})\" src='".root."img/control/list_del.svg'>
</div>";
                if ($has['id']) {
                    $temp .= "<li class='arrow-li' data-id='{$value['id']}' onclick=\"{$data['click']}\">
                                {$arrow}
                                <span class='textcontent'>{$textcontent_ico}{$value['name']}</span>
                                <div class='action-div'>{$dots}</div>
                            </li>";
                    $temp .= self::getDepartmentAll($data);
                } else {
                    $temp .= "<li class='arrow-no-li'  data-id='{$value['id']}' onclick=\"{$data['click']}\">
                                <span class='textcontent'>{$textcontent_ico}{$value['name']}</span>
                                <div class='action-div'>{$dots}</div>
                            </li>";
                }
            }
        }
        $temp .= '</ul>';
        return $temp;
    }

    /**
     * 异步加载
     *
     */
    public function homeRightJson(): bool|string
    {
        $json['html'] = $this->homeRight();
        return json_encode($json, 320);
    }

    public function homeRightJsonSearch(): bool|string
    {
        return $this->homeSearch();
    }

    /**
     * 左侧搜索框
     *
     * @return string
     */
    public function getContainerLeftJson(): string
    {
        $option['click'] = 'replaceContent(this, \'cabinet\')';
        $json['html'] = self::getDepartmentAll($option);
        return json_encode($json, 320);
    }


    /*列表页-查询条件*/
    public function home()
    {
        //返回
        $rightHtml = $this->homeRight();
        $option['click'] = 'replaceContent(this, \'cabinet\')';
        $all = self::getDepartmentAll($option);
        $html = componentClass::leftNav([
            'title'=>'搜索分类',
            'click'=>$option['click'],
            'edit'=>1,
            'allTitle'=>'全部分类',
            'button'=>"<img class='tool-img' title='添加分类' onclick=\"layer('" . self::page . "','catalog',{id:'" . suiji() . "', pid: 0})\" src='".root."img/control/list_add.svg'>",
            'all'=>$all,
            'rightHtml'=>$rightHtml,
        ]);
        $html .= <<<EOT
<style>
.container-main .container-left .action-div {width: 100px!important;margin-left: 5px;}
.container-main .container-left .classify-area .actionBlock {width: 100px!important;}
</style>
EOT;
        //返回
        return $this->homeFun($html);
    }

    public function catalog(): bool|string
    {
        //数据查询
        $info = query(self::table_cabinet, " id = '" . $this->post('id') . "' ");
        $pid = $info['pid'] ?: ($this->post('pid') ?: '0');
        //表单
        $html = $this->layerEdit([
            "table" => [
                [
                    must . "位置：" => text(["name" => "name", "value" => $info['name'], 'class' => 'text']),
                ],
                [
                    "排序号：" => text(["name" => "list", "value" => $info['list'], 'class' => 'text']) . hidden(['name' => 'pid', 'value' => $pid]),
                ]
            ]
        ]);
        //返回
        return $this->layer(["title" => "编辑库位", "height" => 220, "html" => $html]);
    }

    public function catalogEdit(): bool|string
    {
        $id = $this->post('id') ?: self::getId();
        //赋值
        $field = [
            'pid' => $this->post('pid') ?: '0',
            "name" => $this->post('name'),      //部门名称
            "list" => $this->post('list'),      //排序号
        ];
        $info = query(self::table_cabinet, " id = '" . $id . "' ");
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑的权限";
        } elseif (empty($field['name'])) {
            $json['warn'] = "请填写位置名称";
        } elseif (static::total(array('table' => self::table_cabinet, 'where' => "id !='$id' and name = '$field[name]' and pid = '$field[pid]'")) > 0) {
            $json['warn'] = "已经存在此位置名称";
        } elseif (empty($info['id'])) {
            $field = array_merge($field, ["id" => $id]);
            $json['warn'] = insert(["table" => self::table_cabinet, "field" => $field]);
        } else {
            $json['warn'] = update(["table" => self::table_cabinet, "field" => $field, "where" => "id = '" . $id . "'"]);
        }
        if (in_array($json['warn'], array("新增成功", "更新成功"))) {
            //添加日志
            $type = mb_substr($json['warn'], 0, 2, 'utf-8');
            $text = $this->control['name'] . $type . "了一个位置：" . $field['name'];
            $this->logText(array("type" => self::page, "text" => $text));
            //提示
            $_SESSION['warn'] = $json['warn'];
            $json['warn'] = 2;
        }
        //返回
        return json_encode($json, 320);
    }

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'locationId'          => [
                        'name'  => '存放位置',
                        'width' => 100,
                    ],
                    'fileBtn' => [
                        'name'  => "附件数量",
                        'width' => 100,
                    ],
                    'serialStr'  => [
                        'name'  => "全宗号",
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'department'         => [
                        'name'  => '部门名称',
                        'width' => 100,
                    ],
                    'orderNo'          => [
                        'name'  => '归档号',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'archiveYear'          => [
                        'name'  => '归档年度',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'name'          => [
                        'name'  => '题名',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'pageNum'          => [
                        'name'  => '页数',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'partNum'          => [
                        'name'  => '份数',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'fileDate'          => [
                        'name'  => '文件形成日期',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'level'          => [
                        'name'  => '密级',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'stid'          => [
                        'name'  => '归档人',
                        'width' => 100,
                    ],
                    'archiveDate'          => [
                        'name'  => '归档日期',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'typeId'      => [
                        'name'  => "档案分类",
                        'width' => 100,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        $typeId = $this->post('objId') ?? null;
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "归档号" => text(array("name" => "orderNo")).hidden(array('name' => 'locationId', 'value' => $typeId)),
                    "全宗号"     => select(array('name' => 'serialStr', 'option' => explode(',', para('serialStr')))),
                    '部门名称' => selectMultiple(array("name" => "departmentId", 'table' => "department", 'sqlId' => 'id', 'sqlField' => 'name', 'class' => 'width200')),
                ],
                [
                    '归档年度'   => text(array('name' => 'archiveYear', 'laydate' => ['type' => 'year'])),
                    "保管期限" => select(array('name' => 'saveTime', 'option' => explode('，', para('archiveSaveTime')))),
                    '题名'   => text(array("name" => "name")),
                ],
                [
                    "密级" => select(array("name" => "secretLevel", "option" => explode('，', para('secretLevelOption')))),
                    "归档日期" => text(array("name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                    "分类" => selectMultiple(array("name" => "typeId", 'table' => "archive_type", 'sqlId' => 'id', 'sqlField' => 'name', 'class' => 'width200')),
                ]
            ]
        ],1);
        //返回
        if(!$isAsync){
            return $html;
        }else{
            return json_encode(['html'=>$html],320);
        }
    }

    public function homeRight()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"layer('{$this->get('cla')}','move',{})\" class='spanButton'>移出库位</span>\n";
        }
        //返回
        return $this->search($html,layout: 'pop',toolButton: $button);
    }

    public function homeSearch(): bool|string
    {
        $like = array(
            "orderNo" => $this->post('orderNo'),//名称
            "name" => $this->post('name'),
        );
        //全等查询数组
        $equal = array(
            "serialStr" => $this->post('serialStr'),//状态
            "typeId" => $this->post('typeId'),//类型
            "departmentId" => $this->post('departmentId'),
            "archiveYear" => $this->post('archiveYear'),
            "saveTime" => $this->post('saveTime'),
            "secretLevel" => $this->post('secretLevel'),
            "locationId" => $this->post('locationId'),
        );
        $and = "and fileState !=2";
        if ($this->post('createTime')) {
            $and .= self::timeComparison($this->post('createTime'), field: 'archiveDate');
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page;
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . root . "control/adIndex.html?cla=dossier&fun=detail&id=" . $array['id'] . "')"),
            );
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "typeId":
                        $row[] = dossierClass::getTypeName($array['typeId']);
                        break;
                    case "fileBtn":
                        if ($array['source'] == '归档管理') {
                            $archive = query('archive', "id = '$array[sourceId]'");
                            $num = static::total(array('table' => 'file', 'where' => "targetId = '" . $archive['targetId'] . "'"));
                            $fileBtn = $num > 0 ? "<span class='link' onclick=\"layer('component','fileDetail',{id:'" . $archive['targetId'] . "'})\">" . $num . "</span>" : '';
                        } else {
                            $num = static::total(array('table' => 'file', 'where' => "targetId = '" . $array['id'] . "'"));
                            $fileBtn = $num > 0 ? "<span class='link' onclick=\"layer('component','fileDetail',{id:'" . $array['id'] . "'})\">" . $num . "</span>" : '';
                        }
                        $row[] = $fileBtn;
                        break;
                    case "department":
                        $department = query('department', "id = '$array[departmentId]'");
                        $row[] = $department['name'];
                        break;
                    case "locationId":
                        $row[] = dossierClass::getPosititonName($array['locationId']);
                        break;
                    case "stid":
                        $row[] = self::findStaff($array['stid']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $totalQuery = find([
            'table'  => self::table,
            'single' => $where,
            'field'  => "ifnull(sum(partNum),0) as partNum",
        ]);
        $total    = [
            'partNum'        => $totalQuery['partNum'],
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton,"width" => 150),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
        //返回
        $json['html'] = "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        $json['html'] .= <<<efo
<script>

//分类下拉菜单页面
$(".dots").click(function(event) {
    $(".stateBlock").hide();
    let obj = $(this).find(".stateBlock");
      let state = obj.css('display');
    if (state == 'block') {
        obj.hide();
    } else {
        obj.show();
    }
　　　event.stopPropagation()
})
 //点击非下拉区域隐藏
$(document).bind('click', function (e) {
    let target = $(".stateBlock");
    if(!target.is(e.target) && target.has(e.target).length ===0){
      clearDiv();
    }
});
 function clearDiv(){
      $(".stateBlock").hide();
 }
</script>
efo;

        return json_encode($json, 320);
    }

    /**
     * 启用/停用
     */
    public function move(): bool|string
    {
        //生成表单
        $html = $this->layerEdit(array("table" => array(
            array(
                "提示：" => "是否确定把所选档案移出库位？",
            ),
        )));
        //返回
        return $this->layer(array("title" => "移出库位", "height" => 165, "html" => $html, 'formTwo' => 'listForm'));
    }

    /**
     * 启用/停用
     */
    public function moveEdit(): bool|string
    {
        $idArr = $this->post('id') ? [$this->post('id')] : $this->post('listId');
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有" . self::title . "的编辑权限";
        } elseif (empty($idArr) || !is_array($idArr)) {
            $json['warn'] = "请选择数据";
        } else {
            $x = 0;
            $text = '';
            $archive_cabinet = query(self::table_cabinet, "isDefault = 1");
            $field = [
                'locationId' => $archive_cabinet['id'],
            ];
            foreach ($idArr as $id) {
                $info = query(self::table, "id = '$id'");
                if ($info['locationId'] == $field['locationId']) {
                    $text .= "档案【{$info['orderNo']}】-【{$info['name']}】移出库位失败：已在默认库位中<br>";
                } else {
                    $warn = static::update(array(
                        'table' => self::table,
                        'field' => $field,
                        'where' => "id = '$info[id]'"
                    ));
                    if ($warn == '更新成功') {
                        $x++;
                        $text .= "档案【{$info['orderNo']}】-【{$info['name']}】移出库位成功<br>";
                    } else {
                        $text .= "档案【{$info['orderNo']}】-【{$info['name']}】移出库位失败：更新失败<br>";
                    }
                }
            }
            if ($text) {
                $text = $this->control['name'] . "移出库位结果如下：" . $text;
                $this->logText(["type" => self::page, "text" => $text]);
            }
            //返回
            $_SESSION['warn'] = "成功移出了{$x}个档案，详情请查看日志";
            $json['warn'] = 2;
        }
        //返回
        return json_encode($json, 320);
    }

    // 操作中转
    public function operate(): bool|string
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        $form = $power = $word = '';
        switch ($act) {
            case 'delType':
                $act = 'del';
                $msg = '删除分类';
                $title = self::page . 'TypeDelete';
                $function = 'deleteType';
                $form = self::page . 'OperateForm';
                $power = '';
                break;
            default:
                $act = 'del';
                $msg = '删除' . self::title;
                $title = self::page . 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = '你还没有' . $msg . '的权限';
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 删除分类
     * @return bool|string
     */
    public function deleteType(): bool|string
    {
        $array = $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = "你没有删除的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table_cabinet, " id = '$id' ");
                if($info['isDefault']){
                    $warn = "删除失败：此库位是默认库位";
                }elseif ($this->juagdeFile($id)) {
                    $warn = "删除失败：此库位下存在档案";
                } else {
                    //递归删除
                    $this->deleteAll($id);
                    //返回
                    $warn = "删除成功";
                    $x++;
                }
                $text .= "档案库位【" . $info['name'] . "】" . $warn . "。<br>";
            }
            //添加日志
            $text = $this->control['name'] . "删除了档案库位，结果如下：<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = "成功删除{$x}个档案库位，详情请查看日志";
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }

    /**
     * 判断此分类或子分类下是否还存在物料
     * @param $typeId
     */
    public function juagdeFile($typeId): bool
    {
        $material_type = query(self::table_cabinet, "pid = '$typeId'");
        if ($material_type['id']) {
            if (static::total(array('table' => self::table, 'where' => "locationId = '$typeId'")) > 0) {
                return true;
            } else {
                return $this->juagdeFile($material_type['id']);
            }
        } else {
            return false;
        }
    }

    public function deleteAll($id)
    {
        $material_type = query(self::table_cabinet, "pid = '$id'");
        if ($material_type['id']) {
            $this->deleteAll($material_type['id']);
        }
        delete(array('table' => self::table_cabinet, 'where' => "id = '$id'"));
    }


}
